using System;
using System.Collections.Generic;
using UnityEngine;
using QFramework;
using Sirenix.OdinInspector;
using Sirenix.Serialization;
using UnityEngine.Serialization;
using Random = UnityEngine.Random;

namespace Survivor
{
	/// <summary>
	/// 敌人生成信息
	/// 初次访问时，需要调用Reset，将实际生成权重设置为默认权重
	/// </summary>
	[Serializable]
	public class RandomInfo 
	{
		public GameObject prefab;
		[ShowInInspector,LabelText("默认权重")] public int generateDefaultWeight;
		[ShowInInspector,LabelText("当前权重")] public int generateWeight;  // 生成概率权重
		
		/// <summary>
		/// 重置概率权重
		/// </summary>
		public void Reset()
		{
			generateWeight = generateDefaultWeight;
		}
	}

	public partial class EnemyGenerator : ViewController
	{
		private float _currentSeconds = 0;
		// 生成距离玩家距离
		[Header("生成距离")]
		public float generateMinDistance = 5f;
		public float generateMaxDistance = 8f;
		// 生成间隔
		[Header("生成间隔")]
		public float generateDefaultInterval;
		public float currentGenerateInterval;
		[TableList(ShowIndexLabels = true)] public List<RandomInfo> generateInfoList = new ();
		[ShowInInspector,LabelText("比重前缀和"),ReadOnly,SerializeField] private List<int> preWeightSum = new(); // 生成比重前缀和，用于随机生成敌人的概率映射
		public static BindableProperty<int> EnemyNum = new BindableProperty<int>(0);
		public static EnemyGenerator Instance;
		[Header("生成参数")] 
		public float enemyHealthScale = 1;

		public int generateNum = 1;
		

		private void Awake()
		{
			Instance = this;
			EnemyNum.Value = 0;
		}

		void Start()
		{
			currentGenerateInterval = generateDefaultInterval;
			if (generateInfoList.Count !=0)
			{
				generateInfoList[0].Reset(); 
				preWeightSum.Add(generateInfoList[0].generateWeight);
				for (int i = 1; i < generateInfoList.Count; i++)
				{
					generateInfoList[i].Reset();
					preWeightSum.Add(preWeightSum[i-1]+generateInfoList[i].generateWeight);
				}
			}
		}

		private void OnDestroy()
		{
			Instance = null;
		}

		private void Update()
		{
			if (Global.CurrentTime.Value>Global.GameWinAliveTime) return;
			_currentSeconds += Time.deltaTime;
			if (_currentSeconds >= currentGenerateInterval)
			{
				for (int i = 0; i < generateNum; i++)
				{
					GenerateEnemy(GetRandomEnemyIndex());
				}
				_currentSeconds = 0f;
			}
			//Test
			// enemyHealthScale = Mathf.Lerp(1, 3,  Mathf.Clamp(Global.CurrentTime.Value / 200f,0,1));
			// generateNum =Mathf.FloorToInt(Mathf.Lerp(2, 10, Mathf.Clamp(Global.CurrentTime.Value / 100f, 0, 1)));
		}

		public int GetRandomEnemyIndex()
		{
			int sumWeight = preWeightSum[^1];  // 最后一个
			int ramdom = Random.Range(0, sumWeight);
			for (int i = 0; i < preWeightSum.Count; i++)
			{
				if (ramdom < preWeightSum[i])
				{
					return i;
				}
			}
			return 0;
		}

		public void GenerateEnemy(int index)
		{
			if (generateInfoList.Count == 0) return;
			var angle = Random.Range(-180,180);
			var distance = Random.Range(generateMinDistance, generateMaxDistance);
			if (!Player.Default) return;
			var center = Player.Default.transform.position;
			var generatePosition = new Vector2(center.x + distance * Mathf.Cos(angle / 180f * Mathf.PI),
				center.y + distance * Mathf.Sin(angle / 180f * Mathf.PI));
			var enemy = generateInfoList[index].prefab;
			enemy.Instantiate().Position(generatePosition).Show().Self((self) =>
			{
				var enemy = self.GetComponent<Enemy>();
				if (enemy)
				{
					enemy.InitHp(Mathf.CeilToInt(enemy.hp * enemyHealthScale));
				}
			});
		}

		public void SetGenerateWeight(int index, int weight,bool isIncrement = false)
		{
			
			if (index < generateInfoList.Count)
			{
				if (isIncrement)
				{
					generateInfoList[index].generateWeight += weight;
				}
				else
				{
					generateInfoList[index].generateWeight = weight;
				}
				for (int i = 0; i < preWeightSum.Count; i++)
				{
					if (i == 0) preWeightSum[i] = generateInfoList[i].generateWeight;
					else preWeightSum[i] = preWeightSum[i - 1] + generateInfoList[i].generateWeight;
				}
			}
		}
	}
}
